package com.gwz.cardserver.dto.room;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.gwz.cardserver.dto.ResBase;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class MatchRoom {
    /**
     * 房间id
     */
    private int id;
    /**
     * 用户id
     */
    private ConcurrentHashMap<String, ChannelHandlerContext> uids;
    /**
     * 准备用户id
     */
    private List<String> readyUids;


    public MatchRoom(int id) {
        this.id = id;
        this.uids = new ConcurrentHashMap<>();
        this.readyUids = new ArrayList<>();

    }

    /**
     * 房间是否满了
     *
     * @return
     */
    public boolean isFull() {
        return uids.size() == 3;
    }

    /**
     * 房间是否空
     *
     * @return
     */
    public boolean isEmpty() {
        return CollUtil.isEmpty(uids);
    }

    public boolean isAllReady() {
        return readyUids.size() == 3;
    }

    /**
     * 进入房间
     *
     * @param uid
     */
    public void enter(String uid, ChannelHandlerContext context) {
        uids.put(uid, context);
    }

    /**
     * 离开房间
     *
     * @param uid
     */
    public void leave(String uid) {
        uids.remove(uid);
        readyUids.remove(uid);
    }


    /**
     * 玩家准备
     *
     * @param uid
     */
    public void ready(String uid) {
        readyUids.add(uid);
    }

    /**
     * 广播房间内的所有玩家信息
     */
    public void brocast(ResBase resBase, ChannelHandlerContext exChannel) {
        uids.forEach((k, v) -> {
            if (exChannel != v)
                v.write(JSON.toJSONString(resBase));
                v.flush();
        });
    }

}
